﻿using System.Linq;
using eProject.Model;

namespace eProject.ViewModel.Commands
{
    public class ChangeActivityCommand : ICommand
    {
        private readonly CommonManager _manager;
        private readonly Period _newPeriod;        
        private readonly Period _oldPeriod;
        private readonly string _taskName;
        private readonly string _employeeEmail;
        private readonly int _oldPriority;
        private readonly int _newPriority;
        private readonly string _newDescription;
        private readonly string _oldDescription;

        private bool _isCanceled;
        private bool _isExecuted;

        public ChangeActivityCommand(CommonManager manager, ActivityViewModel activity, Period newPeriod) : this(manager, activity,newPeriod,activity.Priority, activity.Description)
        {
            //Do Nothing
        }       

        public ChangeActivityCommand(CommonManager manager, ActivityViewModel activity, Period newPeriod, int newPriority, string newDescription)
        {
            _manager = manager;
            _newPeriod = newPeriod;
            _oldPeriod = activity.Period;
            _employeeEmail = activity.Employee.EMail;
            _taskName = activity.Task.Name;
            _newPriority = newPriority;
            _oldPriority = activity.Priority;
            _newDescription = newDescription;
            _oldDescription = activity.Description;
        }

        public void Execute()
        {
            if (_isExecuted) return;
            var empl = _manager.GetEmployee(_employeeEmail);
            var task = _manager.GetTask(_taskName);
            var acts = _manager.Activities.Where(
                a => a.Task == task && a.Employee == empl && a.Period.Equals(_oldPeriod) && a.Priority == _oldPriority && a.Description == _oldDescription).ToList();
            var act = acts.First();
            act.Period =  _newPeriod;
            act.Description = _newDescription;
            act.Priority = _newPriority;
            _isExecuted = true;
            _isCanceled = false;
        }

        public void Unexecute()
        {
            if (_isCanceled) return;
            var empl = _manager.GetEmployee(_employeeEmail);
            var task = _manager.GetTask(_taskName);
            var acts = _manager.Activities.Where(
                a => a.Task == task && a.Employee == empl && a.Period.Equals(_newPeriod) && a.Priority == _newPriority && a.Description == _newDescription).ToList();
            var act = acts.First();
            act.Period = _oldPeriod;
            act.Description = _oldDescription;
            act.Priority = _oldPriority;
            _isCanceled = true;
            _isExecuted = false;
        }
    }
}
